import { ref, reactive, defineComponent, computed, nextTick, onMounted, watch } from 'vue';
import { useDraggable } from './hooks/use-draggable';
import { Switch, Select, Col } from '@jecloud/ui';
import { encode, decode, getDDItemInfo } from '@jecloud/utils';
import VueEvent from '@/helper/event';
import elementResizeDetectorMaker from 'element-resize-detector';
import { columns as columnOptions } from './hooks/config';

export default defineComponent({
  name: 'DargContainerField',
  components: { Col },
  inheritAttrs: false,
  props: {
    data: {
      type: Object,
      default() {
        return {};
      },
    },
    columns: { type: String, default: '1' },
  },
  setup(props) {
    const { dragClass, removeFn } = useDraggable({ owner: 'field', props });

    let colRef = ref('');
    let width = ref('');
    let peiseRef = ref('');

    let config = decode((props.data.RESOURCEFIELD_OTHERCONFIG || undefined) ?? '{}') ?? {};
    let otherCfgs = reactive({
      titleWidth: config.titleWidth || '', //组内标题宽
      bgColor: config.bgColor || '', //分组框背景
      titleColor: config.titleColor || '', //标题色
      titleBgColor: config.titleBgColor || '', //标题背景色
      borderColor: config.borderColor || '', //边框色
    });

    // 监听变化
    watch(
      () => otherCfgs,
      (newVal) => {
        if (newVal) {
          config = decode(newVal ?? '{}') ?? {};

          Object.keys(otherCfgs).forEach((item) => {
            otherCfgs[item] = config[item];
          });
        }
      },
    );

    let spanNumber = computed(() => {
      if (props.data.RESOURCEFIELD_COLSPAN >= props.columns) {
        // eslint-disable-next-line vue/no-mutating-props
        props.data.RESOURCEFIELD_COLSPAN = props.columns;
      }

      // 子功能 ｜ 审批记录独占一行
      if (['child', 'workflowhistory'].includes(props.data.RESOURCEFIELD_XTYPE)) {
        return 24;
      } else {
        return Math.ceil((props.data.RESOURCEFIELD_COLSPAN / props.columns) * 24);
      }
    });

    let style = ref({});
    let isShowColorScheme = ref(false);

    const showColorScheme = () => {
      let obj = peiseRef.value.getBoundingClientRect();
      if (window.innerHeight - obj.top < 300) {
        style.value.top = obj.top - 300 + 'px';
      } else {
        style.value.top = obj.top + 30 + 'px';
      }

      style.value.left = obj.left - 230 + 'px';

      isShowColorScheme.value = !isShowColorScheme.value;
    };

    const hideColorScheme = (e) => {
      isShowColorScheme.value = false;
      e.stopPropagation();
    };

    const colorSchemeStopPropagation = (e) => {
      e.stopPropagation();
    };

    const erd = elementResizeDetectorMaker();
    onMounted(() => {
      erd.listenTo(colRef.value, (element) => {
        nextTick(() => {
          // 实时获取宽度，以此显示决定是否显示某些元素
          width.value = element.offsetWidth;
        });
      });
    });

    let isAllow = computed(() => {
      return props.data.RESOURCEFIELD_REQUIRE === '1';
    });

    let isReadOnly = computed(() => {
      return props.data.RESOURCEFIELD_READONLY === '1';
    });

    const handleChangeAttrValue = (key, value) => {
      otherCfgs[key] = value;

      // eslint-disable-next-line vue/no-mutating-props
      props.data.RESOURCEFIELD_OTHERCONFIG = encode(otherCfgs);
    };

    const handleChangeAttrValue2 = (key, value) => {
      // eslint-disable-next-line vue/no-mutating-props
      props.data[key] = value ? '1' : '0';
    };

    const handleChangeAttrValue3 = (key, value) => {
      if (value >= props.columns) {
        // eslint-disable-next-line vue/no-mutating-props
        props.data[key] = props.columns;
      } else {
        // eslint-disable-next-line vue/no-mutating-props
        props.data[key] = value;
      }
    };

    const handleClick = () => {
      VueEvent.emit('showEditFormFieldConfig', props.data);
    };

    const textareaKeydown = (event) => {
      if (event.ctrlKey && event.keyCode === 13) {
        //ctrl+enter
        event.preventDefault(); // 阻止浏览器默认换行操作
        return false;
      } else if (event.keyCode === 13) {
        //enter
        event.preventDefault(); // 阻止浏览器默认换行操作
        return false;
      }
    };
    const clickTechGrey = () => {
      // 框内背景颜色: #FFFFFF 标题色：#3F3F3F 标题背景色：#F5F5F5 边框色：#D9D9D9
      otherCfgs.bgColor = '#FFFFFF';
      otherCfgs.titleColor = '#3F3F3F';
      otherCfgs.titleBgColor = '#EFEFEF';
      otherCfgs.borderColor = '#EFEFEF';
      // eslint-disable-next-line vue/no-mutating-props
      props.data.RESOURCEFIELD_OTHERCONFIG = encode(otherCfgs);
    };

    const handleBlurTxt = (e) => {
      // eslint-disable-next-line vue/no-mutating-props
      props.data.RESOURCEFIELD_NAME = e.target.innerHTML;
    };
    const getPopupContainer = () => {
      return document.body;
    };

    const getClass = (data) => {
      return getDDItemInfo('JE_FUNC_FIELD_XTYPE', data.RESOURCEFIELD_XTYPE)?.icon || '';
    };

    return () => (
      <Col span={spanNumber.value} key={props.data.id} data-id={props.data.id} data-type="field">
        {/* 别删，解决单击元素周围的任意位置，contenteditable 也会生效的问题*/}
        <div style={{ height: '0.1px', overflow: 'hidden' }}>1111</div>

        {['child', 'workflowhistory'].includes(props.data.RESOURCEFIELD_XTYPE) ? (
          <div
            ref={colRef}
            class={['container-field', dragClass, isShowColorScheme.value ? 'filter' : '']}
            style={{
              background:
                otherCfgs.titleBgColor || props.data.RESOURCEFIELD_XTYPE == 'child'
                  ? '#bbefbd'
                  : '#BBCAEF',
              borderColor:
                otherCfgs.borderColor || props.data.RESOURCEFIELD_XTYPE == 'child'
                  ? '#12CB61'
                  : '#678AE1',
            }}
          >
            {width.value > 120 ? (
              <span style={{ display: 'flex', flex: '1', width: 0, 'padding-left': '8px' }}>
                <i onClick={handleClick} class={['icon', getClass(props.data)]}></i>
                <span
                  class={{ text: true }}
                  title={props.data.RESOURCEFIELD_NAME}
                  style={{ color: otherCfgs.titleColor, cursor: 'move' }}
                >
                  {props.data.RESOURCEFIELD_NAME}
                  <span style="font-size: 12px">（不支持拖拽到分组框内）</span>
                </span>
              </span>
            ) : null}

            <div class="actions">
              {/* <span class="peise" ref={peiseRef} onClick={showColorScheme}>
                配色方案 <i class="fal fa-angle-down "></i> &nbsp;&nbsp;
                {isShowColorScheme.value ? (
                  <div class="dropmenuWrap" onClick={hideColorScheme}></div>
                ) : null}
                {isShowColorScheme.value ? (
                  <div
                    class="dropmenu"
                    style={{ top: style.value.top, left: style.value.left }}
                    onClick={colorSchemeStopPropagation}
                  >
                    <Form.Item label="框内背景颜色" name="bgColor">
                      <Color
                        onChange={(e) => handleChangeAttrValue('bgColor', e.target.value)}
                        onSelect={(e) => handleChangeAttrValue('bgColor', e.value)}
                        v-model:value={otherCfgs.bgColor}
                        style={{ width: '150px' }}
                      />
                    </Form.Item>
                    <Form.Item label="边框颜色" name="borderColor">
                      <Color
                        onChange={(e) => handleChangeAttrValue('borderColor', e.target.value)}
                        onSelect={(e) => handleChangeAttrValue('borderColor', e.value)}
                        v-model:value={otherCfgs.borderColor}
                        style={{ width: '150px' }}
                      />
                    </Form.Item>
                    <Form.Item label="标题颜色" name="titleColor">
                      <Color
                        onChange={(e) => handleChangeAttrValue('titleColor', e.target.value)}
                        onSelect={(e) => handleChangeAttrValue('titleColor', e.value)}
                        v-model:value={otherCfgs.titleColor}
                        style={{ width: '150px' }}
                      />
                    </Form.Item>
                    <Form.Item label="标题背景颜色" name="titleBgColor">
                      <Color
                        onChange={(e) => handleChangeAttrValue('titleBgColor', e.target.value)}
                        onSelect={(e) => handleChangeAttrValue('titleBgColor', e.value)}
                        v-model:value={otherCfgs.titleBgColor}
                        style={{ width: '150px' }}
                      />
                    </Form.Item>

                    <div style="text-align: center">
                      <Button type="text" style="text-align: center" onClick={clickTechGrey}>
                        科技灰配色方案
                      </Button>
                    </div>
                  </div>
                ) : null}
              </span> */}
              <i class="fal fa-times remove-icon" onClick={removeFn}></i>
            </div>
          </div>
        ) : null}

        {props.data.RESOURCEFIELD_XTYPE !== 'child' &&
        props.data.RESOURCEFIELD_XTYPE !== 'workflowhistory' ? (
          <div
            ref={colRef}
            class={['container-field', dragClass, isReadOnly.value ? 'readonly' : '']}
            style="padding-left:8px"
          >
            {width.value > 120 ? (
              <span style={{ display: 'flex', flex: '1', width: 0 }}>
                <i onClick={handleClick} class={['icon', getClass(props.data)]}></i>
                <span
                  class={{ required: isAllow.value, text: true }}
                  title={props.data.RESOURCEFIELD_NAME}
                  contenteditable
                  onBlur={handleBlurTxt}
                  onKeydown={textareaKeydown}
                >
                  {props.data.RESOURCEFIELD_NAME}
                </span>
              </span>
            ) : null}

            <div class="actions">
              {width.value > 200 ? (
                <span>
                  <Switch
                    defaultChecked={isAllow.value}
                    mode="checkbox"
                    v-model:value={props.data.RESOURCEFIELD_REQUIRE}
                    label={width.value > 300 ? '必填' : null}
                  ></Switch>
                  <Switch
                    mode="checkbox"
                    defaultChecked={isReadOnly.value}
                    v-model:value={props.data.RESOURCEFIELD_READONLY}
                    label={width.value > 300 ? '只读' : null}
                  ></Switch>
                  &nbsp;&nbsp;
                  <Select
                    allowClear={false}
                    v-model:value={props.data.RESOURCEFIELD_COLSPAN}
                    size="small"
                    options={columnOptions}
                    get-popup-container={getPopupContainer}
                    onChange={(val) => handleChangeAttrValue3('RESOURCEFIELD_COLSPAN', val)}
                  />
                </span>
              ) : null}

              <i class="fal fa-times remove-icon" onClick={removeFn}></i>
            </div>
          </div>
        ) : null}

        {/* 别删，解决单击元素周围的任意位置，contenteditable 也会生效的问题*/}
        <div style={{ height: '0.1px', overflow: 'hidden' }}>1111</div>
      </Col>
    );
  },
});
